import { history } from '@umijs/max';
import { message, notification } from 'antd';

import { stringify } from 'querystring';
import { extend } from 'umi-request';

const apiUmiRequest = extend({
  prefix: '/admin-api',
  // timeout: 1000,
  // headers: {
  //   'Content-Type': 'multipart/form-data',
  // },
});



export const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户登录超时，请重新登录。',
  403: '用户没有权限。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const loginPath = '/login';

const errorHandler = <T extends API.Result>(err: any) => {
  console.log('my.request.errorHandler:', err);

  const status =
    err.response && err.response.status ? err.response.status : err.name;
  const errorText = codeMessage[err.response.status] || err.message;

  const result: API.Result = {
    success: false,
    errorCode: status,
    errorMessage: errorText,
  };

  //message.error(`${result.errorMessage} ${result.errorCode}`);

  // if (status === 403) {
  //   history.push('/exception/403');
  // }

  if (status === 401) {
    const { search, pathname } = history.location;

    if (pathname !== loginPath) {
      if (pathname == '' || pathname == '/') {
        history.push(loginPath);
      } else {
        history.replace({
          pathname: loginPath,
          search: stringify({
            redirect: pathname + search,
          }),
        });
      }
    }
  } else {
    notification.error({
      message: result.errorCode,
      description: result.errorMessage,
    });
  }

  // if (status === 404) {
  //   history.push('/exception/404');
  // }
  // else if (status === 500) {
  //   history.push('/exception/500');
  // }

  return result as T;
};

const checkResult = <T extends API.Result>(resData: T) => {
  console.log('my-request:checkResult:', resData);

  if (resData && resData.success === false && resData.errorMessage) {
    //console.log('my-request:checkResult:message.error');
    if (resData.errorCode && resData.errorCode === '404') {
      const errorPageState: API.Result = {
        success: false,
        errorCode: resData.errorCode,
        errorMessage: resData.errorMessage,
      };
      history.push('/exception/error/404', errorPageState);
    } else {
      message.error(resData.errorMessage);
    }
  }

  return resData;
};

export const get = async <T extends API.Result>(
  url: string,
  params?: { [key: string]: any },
  sorter?: { [key: string]: any },
  filter?: { [key: string]: any },
  options?: { [key: string]: any },
) => {
  return doRequest<T>(url, 'GET', params, sorter, filter, options);
};

export const post = async <T extends API.Result>(
  url: string,
  params?: { [key: string]: any },
  sorter?: { [key: string]: any },
  filter?: { [key: string]: any },
  options?: { [key: string]: any },
) => {
  return doRequest<T>(url, 'POST', params, sorter, filter, options);
};

export const postJson = async <T extends API.Result>(
  url: string,
  params?: { [key: string]: any },
  sorter?: { [key: string]: any },
  filter?: { [key: string]: any },
  options?: { [key: string]: any },
) => {
  let datas = { ...(params || {}), ...(filter || {}) };

  if (sorter) {
    datas.sorters = [];
    for (let item in sorter) {
      datas.sorters.push({
        sortField: item,
        sortDirection: sorter[item],
      });
    }
  }

  //console.log('datas:', datas);

  const promise = apiUmiRequest<T>(url, {
    method: 'POST',
    credentials: 'include',
    requestType: 'json',
    responseType: 'json',
    data: datas,
    ...(options || {}),
  }).then(checkResult);

  if (options && options.skipError) {
    return promise;
  }

  return promise.catch((err) => {
    return errorHandler<T>(err);
  });
};

export const postForm = async <T extends API.Result>(
  url: string,
  params?: { [key: string]: any },
  sorter?: { [key: string]: any },
  filter?: { [key: string]: any },
  options?: { [key: string]: any },
) => {
  let datas = { ...(params || {}), ...(filter || {}) };

  if (sorter) {
    let index = 0;
    for (let item in sorter) {
      datas['sorters[' + index + '].sortField'] = item;
      datas['sorters[' + index + '].sortDirection'] = sorter[item];

      index++;
    }
  }

  console.log('datas:', datas);

  const promise = apiUmiRequest<T>(url, {
    method: 'POST',
    credentials: 'include',
    requestType: 'form',
    responseType: 'json',
    data: datas,
    ...(options || {}),
  }).then(checkResult);

  if (options && options.skipError) {
    return promise;
  }

  return promise.catch((err) => {
    return errorHandler<T>(err);
  });
};

export const doRequest = async <T extends API.Result>(
  url: string,
  method: string,
  params?: { [key: string]: any },
  sorter?: { [key: string]: any },
  filter?: { [key: string]: any },
  options?: { [key: string]: any },
) => {
  let datas = { ...(params || {}), ...(filter || {}) };

  if (sorter) {
    let index = 0;
    for (let item in sorter) {
      datas['sorters[' + index + '].sortField'] = item;
      datas['sorters[' + index + '].sortDirection'] = sorter[item];

      index++;
    }
  }

  //console.log('datas:', datas);

  const promise = apiUmiRequest<T>(url, {
    method: method,
    credentials: 'include',
    params: datas,
    ...(options || {}),
  }).then(checkResult);

  if (options && options.skipError) {
    return promise;
  }

  return promise.catch((err) => {
    return errorHandler<T>(err);
  });
};

export const waitTime = (time: number = 1000) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};


/// Cross orgin get

const crossUmiRequest = extend({
  crossOrigin: true,
  //prefix: '/admin-api',
  // timeout: 1000,
  headers: {
    //'Access-Control-allow-Origin': 'Origin',
    //'Content-Type': 'multipart/form-data',
  },
});

const errorCrossHandler = (err: any) => {
  console.log('my.request.errorHandler:', err);
}

const checkCrossResult = (resData: any) => {
  console.log('my-request:checkResult:', resData);

  //console.log('response: ', JSON.stringify(resData));
  return resData;
};

export const getCross = async(
  url: string,
  params?: { [key: string]: any },
  sorter?: { [key: string]: any },
  filter?: { [key: string]: any },
  options?: { [key: string]: any },
) => {
  let datas = { ...(params || {}), ...(filter || {}) };

  if (sorter) {
    let index = 0;
    for (let item in sorter) {
      datas['sorters[' + index + '].sortField'] = item;
      datas['sorters[' + index + '].sortDirection'] = sorter[item];
      index++;
    }
  }
  console.log('datas:', datas);
  const promise = crossUmiRequest(url, {
    method: 'GET',
    // credentials: 'include',
    // requestType: 'form',
    // responseType: 'json',
    data: datas,
    ...(options || {}),
  }).then(checkCrossResult);
  if (options && options.skipError) {
    return promise;
  }
  return promise.catch((err) => {
    return errorCrossHandler(err);
  });
};